<template>
  <div class="addresses-container">
    <a-page-header title="My Addresses" sub-title="Manage your shipping addresses"/>

    <div class="address-actions">
      <a-button type="primary" @click="showAddAddressModal">Add New Address</a-button>
    </div>

    <a-list
        :data-source="addresses"
        :grid="{ gutter: 16, xs: 1, sm: 1, md: 2, lg: 2, xl: 2, xxl: 2 }"
        :loading="loading"
        :pagination="{
        pageSize: pageSize,
        total: totalAddresses,
        current: currentPage,
        showSizeChanger: true,
        pageSizeOptions: ['6', '12', '24'],
        showTotal: total => `Total ${total} records`,
        onChange: handlePageChange,
        onShowSizeChange: handleSizeChange
      }"
    >
      <template #renderItem="{ item }">
        <a-list-item>
          <a-card hoverable :class="{ 'default-address-card': item.is_default }">
            <template #title>
              <div class="address-title">
                <span>{{ item.name }}</span>
                <a-tag v-if="item.isDefault" color="black" class="default-tag">Default Address</a-tag>
              </div>
            </template>
            <p><strong>{{ item.name }}</strong> {{ item.phone }}</p>
            <p>{{ item.province }} {{ item.city }} {{ item.district }}</p>
            <p>{{ item.detail }}</p>
            <p>{{ item.zipCode }}</p>
            <div class="address-actions-row">
              <a-button type="link" @click="editAddress(item)">Edit</a-button>
              <a-button type="link" @click="handleSetDefaultAddress(item)" v-if="!item.is_default">Set as Default</a-button>
              <a-button type="link" danger @click="deleteAddress(item)" v-if="!item.is_default">Delete</a-button>
            </div>
          </a-card>
        </a-list-item>
      </template>
    </a-list>

    <!-- 添加/编辑地址模态框 -->
    <a-modal
        v-model:open="addressModalVisible"
        :title="isEditingAddress ? 'Edit Address' : 'Add New Address'"
        @ok="saveAddress"
        @cancel="handleModalClose"
        :destroyOnClose="true"
        :maskClosable="false"
        width="600px"
    >
      <AddressForm
          v-if="addressModalVisible"
          ref="addressFormRef"
          :initialData="formData"
          :defaultAddress="isDefaultAddress"
          @update:data="onFormDataUpdate"
          @update:isDefault="onDefaultUpdate"
          @update:phoneValid="onPhoneValidUpdate"
          :key="addressModalKey"
      />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { DownOutlined } from '@ant-design/icons-vue';
// import { getAddressList, updateAddress, addAddress, setDefaultAddressById, deleteAddressById } from '@/api/address';
import { Local } from "@/utils/storage.ts";
import { addAddress as addUserAddress, editAddress as editUserAddress, getAddressList, getDetailAddress, setDefaultAddress as setDefaultAddressApi, deleteUserAddress as deleteAddressById } from "@/api/user";
import { getGoogleMap, getMapInfo } from "@/api";
import { countries } from '@/assets/country/country.ts';
import AddressForm from '@/components/common/AddressForm.vue';

// 地址列表
const addresses = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(6);
const totalAddresses = ref(0);
const defaultAddress = ref(null); // 默认地址缓存

// 模态框相关
const addressModalVisible = ref(false);
const isEditingAddress = ref(false);
const currentEditId = ref(null);
const addressFormRef = ref(null);
const addressModalKey = ref(0); // 新增一个key来强制重新渲染组件

// 表单数据
const formData = ref({
  user_id: Local.get('user_info')?.id || '',
  last_name: '',
  first_name: '',
  name: '',
  address: '',
  county: 'United States',
  province: '',
  city: '',
  zipcode: '',
  phone: '',
  countryCode: '+1',
  country_code: '',
  is_default: 0
});

// 默认地址状态
const isDefaultAddress = ref(false);
// 电话验证状态
const isPhoneValid = ref(false);

// 表单数据更新处理
const onFormDataUpdate = (data) => {
  // 防止循环引用，检查是否有实际变化
  const hasChanges = Object.keys(data).some(key => {
    if (key === 'id' || key === 'user_id') return false;
    return formData.value[key] !== data[key];
  });

  if (hasChanges) {
    // 特别记录country_code的变化
    const countryCodeChanged = data.country_code !== formData.value.country_code;

    // 更新整个表单数据
    formData.value = { ...data };
  }
};

// 默认地址更新处理
const onDefaultUpdate = (value) => {
  if (isDefaultAddress.value !== value) {
    isDefaultAddress.value = value;
    formData.value.is_default = value ? 1 : 0;
  }
};

// 电话验证状态更新
const onPhoneValidUpdate = (valid) => {
  isPhoneValid.value = valid;
};

// 页码变化处理
const handlePageChange = (page, pageSize) => {
  currentPage.value = page;
  fetchAddresses();
};

// 每页条数变化处理
const handleSizeChange = (current, size) => {
  currentPage.value = 1;
  pageSize.value = size;
  fetchAddresses();
};

// 获取地址列表
const fetchAddresses = async () => {
  loading.value = true;
  try {
    const res = await getAddressList({
      page: currentPage.value,
      page_size: pageSize.value
    });
    if (res.code === 200) {
      addresses.value = res.result.data || [];
      totalAddresses.value = res.result.total || 0;
      currentPage.value = res.result.current_page || 1;

      // 查找并缓存默认地址
      const defaultAddr = addresses.value.find(addr => addr.is_default === 1);
      if (defaultAddr) {
        defaultAddress.value = { ...defaultAddr };
        // 将默认地址保存到本地存储
        Local.set('defaultAddress', defaultAddress.value);
      }
    } else {
      addresses.value = [];
      totalAddresses.value = 0;
    }
  } catch (error) {
    addresses.value = [];
    totalAddresses.value = 0;
  } finally {
    loading.value = false;
  }
};

// 显示添加地址模态框
const showAddAddressModal = () => {
  // 先重置数据，再显示模态框
  isEditingAddress.value = false;
  currentEditId.value = null;
  resetForm();
  addressModalKey.value = Date.now(); // 使用时间戳确保唯一性

  // 延迟打开模态框，确保数据准备好
  setTimeout(() => {
    addressModalVisible.value = true;
  }, 50);
};

// 编辑地址
const editAddress = async (address) => {
  isEditingAddress.value = true;
  currentEditId.value = address.id;
  addressModalKey.value = Date.now(); // Use timestamp to ensure unique key
  loading.value = true;

  try {
    // 通过API获取详细地址信息
    const res = await getDetailAddress(address.id);

    if (res.code === 200 && res.data) {
      const addressDetail = res.data;

      // 分割姓名为firstName和lastName
      const nameParts = addressDetail.name ? addressDetail.name.split(' ') : ['', ''];

      // 解析电话号码
      let phoneNumber = '';
      let countryCode = '+1';

      if (addressDetail.phone) {
        // 假设电话号码格式为 +xx xxxxxxxxxx
        const phoneMatch = addressDetail.phone.match(/^(\+\d+)\s*(.*)$/);
        if (phoneMatch) {
          countryCode = phoneMatch[1];
          phoneNumber = phoneMatch[2];
        } else {
          phoneNumber = addressDetail.phone;
        }
      }

      // 填充表单
      formData.value = {
        id: addressDetail.id,
        user_id: Local.get('user_info')?.id || '',
        last_name: addressDetail.last_name || nameParts.slice(1).join(' ') || '',
        first_name: addressDetail.first_name || nameParts[0] || '',
        name: addressDetail.name || '',
        address: addressDetail.address || '',
        county: addressDetail.county || 'United States',
        province: addressDetail.province || '',
        city: addressDetail.city || '',
        zipcode: addressDetail.zipcode || '',
        phone: phoneNumber,
        countryCode: countryCode,
        country_code: addressDetail.country_code || '',
        is_default: addressDetail.is_default ? 1 : 0
      };

      // 设置默认地址开关状态
      isDefaultAddress.value = addressDetail.is_default === 1;
      isPhoneValid.value = !!addressDetail.phone;
    } else {
      // 如果API请求失败，回退到使用列表中的数据
      // 分割姓名为firstName和lastName
      const nameParts = address.name.split(' ');

      // 解析电话号码
      let phoneNumber = '';
      let countryCode = '+1';

      if (address.phone) {
        // 假设电话号码格式为 +xx xxxxxxxxxx
        const phoneMatch = address.phone.match(/^(\+\d+)\s*(.*)$/);
        if (phoneMatch) {
          countryCode = phoneMatch[1];
          phoneNumber = phoneMatch[2];
        } else {
          phoneNumber = address.phone;
        }
      }

      // 填充表单
      formData.value = {
        id: address.id,
        user_id: Local.get('user_info')?.id || '',
        last_name: nameParts.slice(1).join(' ') || '',
        first_name: nameParts[0] || '',
        name: address.name,
        address: address.address || '',
        county: address.county || 'United States',
        province: address.province || '',
        city: address.city || '',
        zipcode: address.zipcode || '',
        phone: phoneNumber,
        countryCode: countryCode,
        country_code: address.country_code || '',
        is_default: address.is_default ? 1 : 0
      };

      // 设置默认地址开关状态
      isDefaultAddress.value = address.is_default === 1;
      isPhoneValid.value = !!address.phone;
    }
  } catch (error) {
    console.error('Get address details failed:', error);
    message.error('Get address details failed, please try again later');

    // 出错时使用列表中的数据
    const nameParts = address.name.split(' ');

    // 解析电话号码
    let phoneNumber = '';
    let countryCode = '+1';

    if (address.phone) {
      // 假设电话号码格式为 +xx xxxxxxxxxx
      const phoneMatch = address.phone.match(/^(\+\d+)\s*(.*)$/);
      if (phoneMatch) {
        countryCode = phoneMatch[1];
        phoneNumber = phoneMatch[2];
      } else {
        phoneNumber = address.phone;
      }
    }

    formData.value = {
      id: address.id,
      user_id: Local.get('user_info')?.id || '',
      last_name: nameParts.slice(1).join(' ') || '',
      first_name: nameParts[0] || '',
      name: address.name,
      address: address.detail || '',
      county: address.county || 'United States',
      province: address.province || '',
      city: address.city || '',
      zipcode: address.zipCode || '',
      phone: phoneNumber,
      countryCode: countryCode,
      country_code: address.country_code || '',
      is_default: address.is_default ? 1 : 0
    };

    // 设置默认地址开关状态
    isDefaultAddress.value = address.is_default === 1;
    isPhoneValid.value = !!address.phone;
  } finally {
    loading.value = false;
    // 确保先设置好数据后再打开模态窗
    setTimeout(() => {
      addressModalVisible.value = true;
    }, 0);
  }
};

// 保存地址
const saveAddress = async () => {
  if(!isPhoneValid.value && formData.value.phone) {
    message.error("The format of the phone number is incorrect");
    return;
  }

  // 确保姓名和手机号被正确设置
  formData.value.name = `${formData.value.first_name} ${formData.value.last_name}`.trim();
  formData.value.zip_code = formData.value.zipcode;

  // 确保country_code有值
  if (!formData.value.country_code && formData.value.county) {
    // 从国家列表中查找对应的country_code
    const countryList = countries.filter(c => c.status === 'assigned');
    const selectedCountry = countryList.find(c => c.name === formData.value.county);
    if (selectedCountry) {
      formData.value.country_code = selectedCountry.alpha2;
    } else {
      // 默认设置为US
      formData.value.country_code = 'US';
    }
  }

  try {
    const valid = await addressFormRef.value.validate();
    if (!valid) {
      return;
    }

    const submitData = { ...formData.value };

    if (isEditingAddress.value) {
      // 编辑地址
      const res = await editUserAddress(submitData);
      if (res.code === 200) {
        message.success("successfully edited");
        resetForm();
        addressModalVisible.value = false;
        fetchAddresses(); // 重新获取地址列表

        // 如果编辑的是默认地址，更新默认地址缓存
        if (submitData.is_default === 1) {
          defaultAddress.value = { ...submitData };
          Local.set('defaultAddress', defaultAddress.value);
        }
      } else {
        message.error(res.message || "Failed to edit address");
      }
    } else {
      const res = await addUserAddress(submitData);
      if (res.code === 200) {
        message.success("successfully saved");
        resetForm();
        addressModalVisible.value = false;
        fetchAddresses(); // 重新获取地址列表

        // 如果添加的是默认地址，更新默认地址缓存
        if (submitData.is_default === 1) {
          defaultAddress.value = { ...submitData, id: res.data?.id };
          Local.set('defaultAddress', defaultAddress.value);
        }
      } else {
        message.error(res.message || "Failed to add address");
      }
    }
  } catch (error) {
    console.error("Error saving address:", error);
    message.error("Operation failed, please try again later");
    return false;
  }
};

// 重置表单
const resetForm = () => {
  // 清空所有表单数据
  formData.value = {
    user_id: Local.get('user_info')?.id || '',
    last_name: '',
    first_name: '',
    name: '',
    address: '',
    county: 'United States',
    province: '',
    city: '',
    zipcode: '',
    phone: '',
    countryCode: '+1',
    country_code: '',
    is_default: 0
  };

  // 重置状态
  isDefaultAddress.value = false;
  isPhoneValid.value = false;

  // 如果表单引用存在，通过它重置
  if (addressFormRef.value) {
    // 使用try-catch避免可能的错误
    try {
      addressFormRef.value.resetFields();
    } catch (error) {
      console.error("Error resetting form fields:", error);
    }
  }
};

// 添加模态框关闭事件处理函数
const handleModalClose = () => {
  // 使用setTimeout使操作异步执行，避免与关闭动画冲突
  setTimeout(() => {
    resetForm();
    addressModalKey.value++; // 增加key，确保组件重新创建
  }, 100);
};

// 设为默认地址
const handleSetDefaultAddress = async (address) => {
  try {
    const res = await setDefaultAddressApi(address.id);

    if (res.code === 200) {
      message.success(`${address.name} has been set as the default address`);

      // 更新默认地址缓存
      defaultAddress.value = { ...address, is_default: 1 };
      Local.set('defaultAddress', defaultAddress.value);

      fetchAddresses(); // 重新获取地址列表
    } else {
      message.error(res.message || 'Failed to set default address');
    }
  } catch (error) {
    console.error('Failed to set default address:', error);
    message.error('Failed to set default address, please try again later');
  }
};

// 删除地址
const deleteAddress = async (address) => {
  if (address.isDefault) {
    message.error('Default address cannot be deleted');
    return;
  }

  try {
    const res = await deleteAddressById(address.id);

    if (res.code === 200) {
      message.success('Address deleted');
      fetchAddresses(); // 重新获取地址列表
    } else {
      message.error(res.message || 'Failed to delete address');
    }
  } catch (error) {
    console.error('Failed to delete address:', error);
    message.error('Failed to delete address, please try again later');
  }
};

// 组件挂载时获取地址列表
onMounted(() => {
  fetchAddresses();
});
</script>

<style scoped>
.addresses-container {
  padding: 0 10px;
}

.address-actions {
  margin-bottom: 16px;
  text-align: right;
}

.address-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.default-tag {
  font-weight: bold;
  font-size: 14px;
}

.address-actions-row {
  margin-top: 12px;
  display: flex;
  gap: 8px;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

.default-address-card {
  border: 2px solid #000000;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
}

@media (max-width: 1280px) {
  .addresses-container {
    padding: 0 5px;
  }

  .address-actions {
    margin-bottom: 12px;
  }

  .address-actions-row {
    flex-direction: column;
    gap: 5px;
  }

  .address-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>
